/**
 * 用于处理用户相关的业务
 */
var userModel = require("../models/userModel");
//引入加密模块
var crypto = require("../config/crypto");
//引入邮件发送模块
var sendMail = require("../config/email");
//引入检测用户是否登陆的模块
var checkUserLogin = require("../middlewares/checkUserLogin");
//引入日志模型
var logModel = require('../models/logModel');
//引入获取当前ip的方法
var getIp = require('../config/getLocalIp');

var index = {};

//错误-页面
function showError(req,res,title,errStr){
    res.render('./common/error',{
        tempName:'error',
        title: title,
        err: errStr
    });
}

//用户中心-页面
index.goUserCenter = function (req,res) {
    var con = {_id:req.params._id};
    userModel.find(con,function (err,data) {
        if(err){
            res.redirect("/login");
        }else{
            res.render('./user/userCenter', {user:data[0],tempName:'userCenter'});
            //res.send({user:data[0],username:req.session.username,userid:req.session.userid,tempName:'userCenter'});
            //res.redirect('./user/userCenter');
        }
    });
};

//用户注册后的提示email激活-页面
index.tipEmail = function (req,res) {
	res.render('./user/tipEmail',{tempName:'tipEmail'});
};

//用户安全中心-页面
index.goSecurity = function (req,res) {
    res.render('./user/securityCenter',{tempName:'security'});
}

//注册前验证用户名是否唯一
index.verifyUsername = function (req,res) {
    var con = {username:req.body.username};
    userModel.find(con,function (err,msg) {
        if(err || (msg.length == 1) || req.body.username.length == 0){
            res.send({result:0,err:'user name unavailable'});
        }else{
            res.send({result:1,err:''});
        }
    });
};

//注册前验证邮箱是否唯一
index.verifyEmail = function (req,res) {
    var con = {email:req.body.email};
    userModel.find(con,function (err,msg) {
        if(err || (msg.length == 1) || req.body.email.length == 0){
            res.send({result:0,err:'email address unavailable'});
        }else{
            res.send({result:1,err:''});
        }
    });
};

//用户注册
index.register = function (req,res) {
    //console.log(crypto);
    var newUser = {
        username: req.body.username,
        password: crypto(req.body.password),    //密码经过加密
        sex: req.body.sex,
        age: (req.body.age.length == undefined ? 1 : req.body.age),
        email: req.body.email,
        phone: req.body.phone,
        regTime: new Date(),
        active: 0
    };
    var con1 = {username: req.body.username};
    var con2 = {email: req.body.email};
    //进行用户名和邮箱地址唯一性验证
    userModel.find(con1,function (err1,data1) {
        if(data1.length != 0){//验证用户名
            showError(req,res,"Registration Error","Username already exists!");
        }else{
            userModel.find(con2,function (err2,data2) {//验证邮箱
                if(data2.length != 0){
                    //res.render("../common/error", { data: err,username:req.session.username,userid:req.session.userid,tempName:"error",title:"Register Failure"});
                    showError(req,res,"Registration Error",'Email address already exists!');
                }else{
                    //新建用户
                    userModel.create(newUser, function(err, msg) {
                        if (err) {
                            console.log(err);
                            showError(req,res,"Registration Error","Register Failure");
                            //res.render("../common/error", { data: err,tempName:"error",title:"Register Failure"});
                        } else {
                            //res.redirect("/");
                            //发送用户注册验证邮件
                            sendMail(msg._id,msg.username,msg.email,function(err){
                                if(err){
                                    //发送邮件出现错误时的处理, 提示用户邮件发送失败, 去个人中心进行重新发送激活
                                }else{
                                    //跳转提示 用户发送成功页面 提示用户去激活账户
                                    res.render("./user/tipEmail",{tempName:"error"});
                                }
                            });
                        }
                    });
                }
            });
        }
    });
};

//删除用户
index.deleteUser = function (req,res) {
    //console.log(req.body);
    var con = {_id:req.body._id}
    userModel.remove(con,function(err,msg){
        if(err){
            console.log(err);
            res.send("({success:0,info:'An error occured when deleting user.'})");
            return;
        }
        if(msg.ok == 1){
            res.send("({success:1})");
        }else{
            res.send("({success:0,info:'No such user.'})");
        }
    });
};

//登陆
index.login = function (req,res) {

    //console.log(req.body);
    var con = {
        username: req.body.username, 
        password: crypto(req.body.password)
    };
    userModel.find(con, function(err, data) {
        if (err) {
            console.log(err);
        } else {
            //console.log(data);
            if (data.length == 0) {
                showError(req,res,"Login failed","Invalid username or password.");
            } else {
                console.log('== user login: ' + req.body.username);
                //console.log("==set session user: "+ req.session);
                req.session.user = data[0];
                req.session.username = req.body.username;
                req.session.userid = data[0]._id;
                req.session.active = data[0].active;
                //记录最后一次登陆时间
                var con = {_id:data[0]._id};
                var newData = {lastLoginTime:new Date()};
                userModel.update(con,newData,function (err,msg) {
                    if(err){
                        console.log(err);
                    }
                    
                });
                //记录日志
                var newLog = {
                    user: data[0]._id,
                    actType: "login",
                    actDescription:"the user "+data[0].username+" logged in system.",
                    userIp: getIp.getClientIP(req)
                }
                logModel.create(newLog,function (err,msg) {
                    if(err){
                        console.log(err);
                    }
                })
                res.redirect('/');
            }
        }
    });
};

//注销
index.logout = function (req,res) {
    //删除session中的信息
    //delete req.session.username;
    //delete req.session.userid;
    //delete req.session.active;
    req.session.user = undefined;
    req.session.username = undefined;
    req.session.active = undefined; 
    res.redirect('/');
};

//获取用户列表
index.getUserList = function (req,res) {
    userModel.find(function(err, data) {
        //console.log(data);
        res.render('./user/userList', { userList: data ,tempName:'userList'});
        
    });
};

//获取用户信息
index.getUserInfo = function (req,res) {
    //console.log(req.query._id);
    userModel.findOne({_id: req.query._id }, function(err,data) {
        //console.log(data);
        res.send(data);
    });
};

//更新用户信息(返回json值并不刷新页面)
index.updateUserWithoutRefresh = function (req,res) {
    //console.log(req.body);
    var con = {_id:req.body._id};
    var newData = {
        //username: req.body.username,
        sex: req.body.sex,
        email: req.body.email,
        phone: req.body.phone,
        age: (req.body.age == "" ? 0 : req.body.age),
        mark: req.body.mark
    };

    userModel.update(con,newData,function(err,msg){
        if(err){
            console.log(err);
            res.send("({success:0,info:'An error occured when updating.'})");
            return;
        }
        //console.log(msg);
        if(msg.ok == 1){
            userModel.findOne(con,function (err,data) {
                //将修改之后的用户给予session
                req.session.user = data;
            })
            res.send("({success:1})");
        }
    });
};

//更新用户信息(返回)
index.updateUserAndRefresh = function(req,res){
    //console.log(req.body);
    var con = {_id:req.body._id};
    var newData = {
        //username: req.body.username,
        sex: req.body.sex,
        email: req.body.email,
        phone: req.body.phone,
        age: req.body.age
    };

    userModel.update(con,newData,function(err,msg){
        if(err){
            console.log(err);
            showError(req,res,"Internal Server Error","Internal server error, please try again later.");
            return;
        }
        if(msg.ok == 1){
            res.redirect("back");
        }
    });
};

//新注册用户激活
index.goVerifyUser = function (req,res) {
    //console.log(req.params);
    var con = {_id: req.params.id};
    var newData = {active: 1, lastLoginTime:new Date()};
    userModel.find(con,function (err,data) {
        if(data[0].active === 1){//如果用户已激活
            showError(req,res,"Activation Error","Your account has been activated.");
        }else{
            userModel.update(con,newData,function (err,msg) {
                if(err){
                    showError(req,res,"Activation Error","Failed to activate your account, please try again later.");
                }else{
                    res.render('./common/info',{info:'Congrats! You have succeed registered our website, please login!',tempName:'info',title:"Account Activation"});
                }
            });
        }
    });
};

//用户修改密码
index.updatePassword = function(req,res){
    var userid = req.session.user._id;
    //console.log(req.session.user._id);
    var con = {
        _id: userid,
        password: crypto(req.body.oldpassword)
    };
    userModel.findOne(con,function(err,data){
        if(data){
            var newData = {
                _id: userid,
                password: crypto(req.body.newpassword)
            };
            userModel.update(con,newData,function (err,msg) {
                if(err){
                    showError(req,res,"Update password error","Internal server error, please try again later.");
                }else{
                    res.render('./common/info',{info:'Password has been successfully updated.',tempName:'info',title:"Password update"});
                }
            });
        }else{
            showError(req,res,"Update password error","Old password does not match, please check again.");
        }
    });
}

module.exports = index;